import { createContext, useContext, useState, useEffect } from 'react';
import { authService } from '../services';


const AuthContext = createContext(null);

const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(authService.getUser());  

  useEffect(() => {
    const fetchUser = async () => {
      if (authService.isLogin()) {
        setUser(authService.getUser());
      }     
    };

    fetchUser();
  }, []);

  const login = async (httpService,email, password) => {
    const response = await authService.login(httpService,email, password);
    setUser(response);
  };

  const logout = () => {
    authService.logout();
    setUser(null);
  };

  const isLogin = () => {
    return authService.isLogin();
};
  return (
    <AuthContext.Provider value={{ user, login, logout,isLogin }}>
      {children}
    </AuthContext.Provider>
  );
};

const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

export { AuthProvider, useAuth };